/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc.utils;

import cn.yzc.mapper.GoodsMapper;
import cn.yzc.pojo.Orderdetails;
import cn.yzc.pojo.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>Project: redis - RedisKeyExpirationListener</p>
 * <p>Powered by yzc On 2023-12-14 11:02:36</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public void onMessage(Message message, byte[] pattern) {
       // super.onMessage(message, pattern);
        String expiredKey = message.toString();  //获得失效的key
        log.info("..................redis key失效 = {}",expiredKey);
        if (expiredKey.startsWith("order")){
            //key存在，将商品库存恢复
            String orderNo = expiredKey.substring(expiredKey.lastIndexOf(":")+1);
            Orders orders = (Orders) redisTemplate.opsForValue().get(orderNo);
            List<Orderdetails> orderdetailsList = orders.getOrderdetailsList();
            orderdetailsList.forEach(orderdetails -> {
                int num  =  goodsMapper.queryNum(orderdetails.getGoodid());
                int number = orderdetails.getNumber();
                int newNum = num+number;
                goodsMapper.update(orderdetails.getGoodid(), newNum);});
            //删除key
            redisTemplate.delete(orderNo);
        }

    }

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


}
